package video

import (
	"app-api/clients/video"
	"app-api/common/constant"
	"app-api/common/paginate"
	"context"
	"encoding/json"
	"fmt"
	"github.com/jinzhu/copier"
	"math"
	"strconv"

	"app-api/app/internal/svc"
	"app-api/app/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetFavVideoListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetFavVideoListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFavVideoListLogic {
	return &GetFavVideoListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetFavVideoListLogic) GetFavVideoList(req *types.VideoListRequest) (resp *types.VideoListResponse, err error) {
	userID, _ := l.ctx.Value("id").(json.Number).Int64()
	start := paginate.GetOffset(req.Page, req.PerPage)
	userFavVideoKey := fmt.Sprintf("%s:%d", constant.UserFavVideoKey, userID)
	countInt, err := l.svcCtx.Redis.LlenCtx(l.ctx, userFavVideoKey)
	idStrings, err := l.svcCtx.Redis.LrangeCtx(l.ctx, userFavVideoKey, int(start), int(start+req.PerPage))
	var videoIDs []int64
	for _, idString := range idStrings {
		id, _ := strconv.ParseInt(idString, 10, 64)
		videoIDs = append(videoIDs, id)
	}

	videos, err := l.svcCtx.VideoRPC.GetVideoListByIDs(l.ctx, &video.VideoIDsRequest{VideoIds: videoIDs})
	if err != nil {
		return nil, err
	}

	list := make([]types.VideoInfo, len(videos.List))
	for i, v := range videos.List {
		item := types.VideoInfo{}
		_ = copier.Copy(item, v)
		list[i] = item
	}
	count := int64(countInt)
	pages := int64(math.Ceil(float64(count) / float64(req.PerPage)))
	return &types.VideoListResponse{List: list, Total: count, Page: req.PerPage, Pages: pages}, nil
}
